package com.example.demo.sys.service.impl;

import com.example.demo.sys.dao.PermissionMapper;
import com.example.demo.sys.dao.RoleMapper;
import com.example.demo.sys.entity.Permission;
import com.example.demo.sys.entity.Role;
import com.example.demo.sys.service.PermissionService;
import com.example.demo.sys.service.bo.PermissionBO;
import com.example.demo.sys.service.bo.RoleBO;
import com.example.demo.sys.service.dto.RoleConfigDTO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<RoleBO> getRoles() {
        List<Role> roles = roleMapper.getAll();
        List<RoleBO> roleBOS = new ArrayList<>();
        for(int i=0;i<roles.size();i++) {
            roleBOS.add(RoleBO.convert(roles.get(i)));
        }
        return roleBOS;
    }

    @Override
    @Transactional
    public void roleConfig(RoleConfigDTO rc) {
        List<String> users = rc.getUsers();
        List<String> menus = rc.getMenus();
        for(int i=0;i<users.size();i++) {
            Long userId = Long.parseLong(users.get(i));
            // 删除旧权限
            permissionMapper.deleteByUserId(userId);
            for(int j=0;j<menus.size();j++){
                // 添加新权限
                Permission permission = new Permission();
                permission.setRoleId(rc.getRoleId());
                permission.setMenu(menus.get(j));
                permission.setUserId(userId);
                permissionMapper.addPermission(permission);
            }
        }
    }

    @Override
    public List<PermissionBO> getUserPermissions(Long userId) {
        List<Permission> permissions = permissionMapper.getUserPermissions(userId);

        return null;
    }
}
